package com.zhengaz.auth.controller;

import cn.hutool.core.util.StrUtil;
import com.zhengaz.auth.form.LoginForm;
import com.zhengaz.auth.form.RegisterForm;
import com.zhengaz.auth.service.SystemLoginService;
import com.zhengaz.common.core.entity.R;
import com.zhengaz.common.security.auth.AuthUtil;
import com.zhengaz.common.security.service.TokenService;
import com.zhengaz.common.security.utils.SecurityUtils;
import com.zhengaz.model.system.model.LoginUser;
import io.swagger.annotations.Api;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
 * 进入系统控制器
 *
 * @author zhengzg
 * @create 2023-09-14 15:32
 */
@Api(tags = "系统控制器")
@RestController
@RequestMapping("/api")
public class SysInputController {

    @Resource
    private TokenService tokenService;

    @Resource
    private SystemLoginService systemLoginService;

    @PostMapping("/login")
    public R<?> login(@RequestBody LoginForm loginForm) {
        LoginUser login = systemLoginService.login(loginForm);
        return R.ok(tokenService.createToken(login));
    }

    @DeleteMapping("/logout")
    public R<?> logout(HttpServletRequest request) {
        String token = SecurityUtils.getToken(request);
        if (StrUtil.isBlank(token)) return R.fail("登出异常！请联系管理员！");
        // 登出
        AuthUtil.logoutByToken(token);
        return R.ok();
    }

    @PostMapping("/refresh")
    public R<?> refresh(HttpServletRequest request) {
        LoginUser loginUser = tokenService.getLoginUser(request);
        if (Objects.isNull(loginUser)) return R.fail("刷新token失败！请重试！");

        tokenService.refreshToken(loginUser);
        return R.ok();
    }

    @PostMapping("/register")
    public R<?> register(@RequestBody RegisterForm registerForm) {
        systemLoginService.register(registerForm.getUsername(), registerForm.getPassword());
        return R.ok();
    }

}
